<template>
  <el-radio-group
    v-model="selectedValue"
    :size="size"
    :disabled="disabled"
    @change="handleChange"
  >
    <el-radio
      v-for="option in options"
      :key="getOptionValue(option)"
      :label="getOptionValue(option)"
      :disabled="getOptionDisabled(option)"
    >
      {{ getOptionLabel(option) }}
    </el-radio>
  </el-radio-group>
</template>

<script lang="ts" >
import { defineComponent, PropType, computed } from 'vue'

type OptionType = {
  label: string
  value: string | number | boolean
  disabled?: boolean
}

export default defineComponent({
  name: 'MyRadioGroup',
  props: {
    modelValue: {
      type: [String, Number, Boolean] as PropType<string | number | boolean>,
      required: true
    },
    options: {
      type: Array as PropType<OptionType[]>,
      required: true
    },
    size: {
      type: String as PropType<'large' | 'default' | 'small'>,
      default: 'default'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    optionLabel: {
      type: String,
      default: 'label'
    },
    optionValue: {
      type: String,
      default: 'value'
    },
    optionDisabled: {
      type: String,
      default: 'disabled'
    }
  },
  emits: ['update:modelValue', 'change'],
  setup(props, { emit }) {
    const selectedValue = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    })

    const getOptionLabel = (option: OptionType | string | number) => {
      if (typeof option === 'object') {
        return option[props.optionLabel as keyof typeof option] ?? option.label
      }
      return option
    }

    const getOptionValue = (option: OptionType | string | number) => {
      if (typeof option === 'object') {
        return option[props.optionValue as keyof typeof option] ?? option.value
      }
      return option
    }

    const getOptionDisabled = (option: OptionType | string | number) => {
      if (typeof option === 'object') {
        return (
          option[props.optionDisabled as keyof typeof option] ?? option.disabled
        )
      }
      return false
    }

    const handleChange = (value: string | number | boolean) => {
      emit('change', value)
    }

    return {
      selectedValue,
      getOptionLabel,
      getOptionValue,
      getOptionDisabled,
      handleChange
    }
  }
})
</script>
